<?php

namespace app\site\service\store;

use app\common\exception\MiException;
use app\model\ProductCate;
use app\model\store\GoodsCate;
use app\site\service\SiteBaseService;
use app\site\service\traits\InstanceTrait;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\db\Query;
use think\facade\Db;
use think\Model;

class GoodsCateService extends SiteBaseService
{

    use InstanceTrait;

    public function initialize()
    {
        $this->model = new GoodsCate();
    }

    function formatData(array $data): array
    {
        return $data;
    }

    function query(): Query
    {
        return $this->setWith(['parent', 'children'])->makeQuery();
    }


    /** 重写删除操作
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     * @throws MiException
     */
    function delete()
    {
        if (count($this->where) == 0){
            throw new MiException("删除操作必须设置条件");
        }

        Db::transaction(function () {
            $list = $this->query()->lock(true)->select();
            foreach ($list as $v){
                if (count($v->children) > 0){
                    throw new MiException("不能删除带有下级的分类，请先删除最底层分类");
                }
            }
            $this->query()->delete();
        });

    }


    /** 根据分类id获取下级分类
     * @param $arr
     * @param $id
     * @param $lev
     * @return array 一维数组
     */
    public function tree($data,$id=0,$lev=1): array
    {
        $subs = array();
        foreach($data as $v)
        {
            if($v['pid'] == $id){
                $v['lev'] = $lev;
                $v['l_title'] = str_repeat("——", $lev-1).$v['title'];
                $subs[] = $v;
                $subs = array_merge($subs,$this->tree($data, $v['id'], $lev+1));
            }
        }
        return $subs;
    }

    /**
     * 二维数组
     * @param $data
     * @param $id
     * @param $lev
     * @return array
     */
    public function childrenTree($data, $id=0, $lev=1): array
    {
        $subs = array();
        foreach($data as $v)
        {
            if($v['pid'] == $id){
                $v['lev'] = $lev;
                $v['children'] = $this->childrenTree($data, $v['id'], $lev+1);
                $subs[] = $v;
            }
        }
        return $subs;
    }

    /**
     * 获取所有下级分类id
     * @param $data
     * @param $id
     * @return array
     */
    public function childrenIds($data, $id): array
    {
        $tree = $this->tree($data, $id);
        $ids = [];
        foreach ($tree as $v){
            $ids[] = $v['id'];
        }
        return $ids;
    }

}
